package com.dgut.service.background.controller;

import com.alibaba.fastjson.JSON;
import com.dgut.service.background.bean.PassConditions;
import com.dgut.service.background.config.resultConfig.JsonResult;
import com.dgut.service.background.config.resultConfig.ResultTool;
import com.dgut.service.background.entity.Outs;
import com.dgut.service.background.service.OutsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

/**
 * 出门
 */
@RestController
@RequestMapping("outs")
public class OutsController {
    @Autowired
    private OutsService outsService;

    //分页获取所有出门信息
    @GetMapping("allOuts/{page}")
    public String findAllOuts(@PathVariable("page") int page){
        Page<Outs> allOuts = outsService.findAllOuts(page);
        JsonResult result = ResultTool.success(allOuts);
        return JSON.toJSONString(result);
    }

    //通过条件查找出门信息
    @PostMapping("conditions")
    public String findByConditions(PassConditions passConditions){
        String username = passConditions.getUsername();
        String[] towDate = passConditions.getTwoDate();
        //判断日期条件是否为空
        Boolean towDateNull = true;
        if (towDate==null){
            towDateNull = true;
        }else {
            if (towDate[0].length() == 0)
                towDateNull = true;
            else towDateNull = false;
        }
        //获取姓名长度
        int usernameLength = username.length();

        int ASC = passConditions.getASC();
        int page = passConditions.getPage();
        Pageable pageable = null;
        Sort sort = null;
        Page<Outs> outs = null;
        //按时间升序
        if (ASC == 1){
            sort = Sort.by(Sort.Direction.ASC, "times");
            pageable = PageRequest.of(page, 10, sort);
        }else { //按时间降序
            sort = Sort.by(Sort.Direction.DESC, "times");
            pageable = PageRequest.of(page, 10, sort);
        }

        //openid为空、时间为空
        if(usernameLength == 0 && towDateNull){
            outs = outsService.findAllOuts(pageable);
        }
        //openid和时间范围不为空
        else if (usernameLength != 0 && !towDateNull){
            outs = outsService.findAllByTimesBetweenAndUsernameLike(username, towDate, pageable);
        }
        //openid不为空、时间为空
        else if(usernameLength != 0 && towDateNull){
            outs = outsService.findAllByUsername(username, pageable);
        }
        //openid为空、时间不为空
        else if(usernameLength == 0 && !towDateNull){
            outs = outsService.findByDate(towDate[0], towDate[1], pageable);
        }
        JsonResult result = ResultTool.success(outs);
        return JSON.toJSONString(result);
    }
}
